
package member
import (
    "time"
    "errors"
	"strings"
    "dhfshop/models"
	"github.com/astaxie/beego/orm"
)

// 也可以添加有效期的属性：永久有效、每多少个月全部重置等
type MemberLevel struct {
	MemberLevelId int64   `orm:"column(member_level_id);pk;auto" json:"member_level_id" form:"member_level_id"` 
	PartnerId     int64     `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`           //商户编号
	Value         int     `orm:"column(value)" json:"value" form:"value"`                          // 等级值(1,2,4,8,16)
	Name          string  `orm:"column(name)" json:"name" form:"name"`                             //等级名称 
	RequireExp    int     `orm:"column(require_exp)" json:"require_exp" form:"require_exp"`        //所需成长值,基于完成的订单增长
    Enabled       int     `orm:"column(enabled)" json:"enabled" form:"enabled"`                    // 
	CreatedAt   time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`  //创建时间
	UpdatedAt   time.Time `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`      // 修改时间
}

func init() {
    orm.RegisterModel(new(MemberLevel))   
}


// 初始化默认等级
func InitDefaultLevels(partnerId int64, levelSet []*MemberLevel) error {
	if len(levelSet) != 0 {
		return errors.New("已经存在数据，无法初始化!")
	}
	var arr []*MemberLevel = []*MemberLevel{
		&MemberLevel{
			PartnerId:  partnerId,
			Name:       "普通会员",
			RequireExp: 0,
			Value:      1,
			Enabled:    1,
		},
		&MemberLevel{
			PartnerId:  partnerId,
			Name:       "铜牌会员",
			RequireExp: 100,
			Value:      2,
			Enabled:    1,
		},
		&MemberLevel{
			PartnerId:  partnerId,
			Name:       "银牌会员",
			RequireExp: 500,
			Value:      3,
			Enabled:    1,
		},
		&MemberLevel{
			PartnerId:  partnerId,
			Name:       "金牌会员",
			RequireExp: 1200,
			Value:      4,
			Enabled:    1,
		},
		&MemberLevel{
			PartnerId:  partnerId,
			Name:       "白金会员",
			RequireExp: 1500,
			Value:      5,
			Enabled:    1,
		},
	}

	for _, v := range arr {
		SaveMemberLevel(partnerId, v)
	}
	return nil
}

func AddMemberLevel(v *MemberLevel) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

func GetMemberLevelById(id int64) (v *MemberLevel, err error) {
	o := models.GetDefaultDB()
	v = &MemberLevel{MemberLevelId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func UpdateMemberLevel(v *MemberLevel,param ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	m := MemberLevel{MemberLevelId: v.MemberLevelId}
	if err = o.Read(&m); err == nil {
		if id, err = o.Update(v, param...); err == nil {
		    return
		}
	}
	return
}

func DeleteMemberLevel(partnerId, id int64) (err error) {
	o := models.GetDefaultDB()
	v := MemberLevel{PartnerId: partnerId, MemberLevelId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return
		}
	}
	return
}

// 保存等级
func SaveMemberLevel(partnerId int64, v *MemberLevel) (id int64, err error) {
	o := models.GetDefaultDB()
	m := MemberLevel{MemberLevelId: v.MemberLevelId}
	if err = o.Read(&m); err == nil {
		if _, err = o.Update(v); err == nil {
		    id = int64(v.MemberLevelId)
		}
	} else {
	    id, err = o.Insert(v)
	}
	return
}

func GetLevelById(partnerId, id int) (member *MemberLevel) {
	member = &MemberLevel{}
	o := models.GetDefaultDB()
	o.QueryTable(new(MemberLevel)).Filter("partner_id", partnerId).Filter("member_level_id", id).One(member)
	return
}

// 获取等级
func GetLevelByValue(partnerId, levelValue int) (member *MemberLevel) {
	member = &MemberLevel{}
	o := models.GetDefaultDB()
	o.QueryTable(new(MemberLevel)).Filter("partner_id", partnerId).Filter("value", levelValue).One(member)
	return
}

// 获取下一个等级
func  GetNextLevel(partnerId, levelVal int) *MemberLevel {
	var m *MemberLevel
	o := models.GetDefaultDB()
	err := o.Raw("select * from member_level where partner_id=? AND value>? LIMIT 0,1", partnerId, levelVal).QueryRow(m)
	if err != nil {
		return nil
	}
	return m
}

// 获取会员等级
/*
func GetMemberLevels(partnerId int64) (pList []*MemberLevel, err error) {
    o := models.GetDefaultDB()
	_, err = o.QueryTable(new(MemberLevel)).Filter("partner_id", partnerId).All(&pList)
	return
}
*/

func GetAllMemberLevels(partnerId int64,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*MemberLevel,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(MemberLevel))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	qs = qs.Filter("partner_id", partnerId)
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*MemberLevel
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

/*
// 获取积分对应的等级
func  GetLevelValueByExp(partnerId int64, exp int) int {
	var levelId int
	this.Connector.ExecScalar(`SELECT lv.value FROM pt_member_level lv
	 	where lv.partner_id=? AND lv.require_exp <= ? AND lv.enabled=1
	 	 ORDER BY lv.require_exp DESC LIMIT 0,1`,
		&levelId, partnerId, exp)
	return levelId
}
*/


/*
// 获取下级会员数量
func  GetSubInvitationNum(memberIds string) map[int]int {
	var d map[int]int = make(map[int]int)
	err := this.Connector.Query(fmt.Sprintf("SELECT r1.member_id,"+
		"(SELECT COUNT(0) FROM mm_relation r2 WHERE r2.invi_member_id=r1.member_id)"+
		"as num FROM mm_relation r1 WHERE r1.member_id IN(%s)", memberIds),
		func(rows *sql.Rows) {
			var id, num int
			for rows.Next() {
				rows.Scan(&id, &num)
				d[id] = num
			}
			rows.Close()
		})

	if err != nil {
		log.PrintErr(err)
	}
	return d
}

*/
/*
// 检查升级
func (m *memberImpl) checkLevelUp() bool {
	lg := m.manager.LevelManager()
	levelId := lg.GetLevelIdByExp(m.value.Exp)
	if levelId == 0 {
		return false
	}
	// 判断是否大于当前等级
	if m.value.Level > levelId {
		return false
	}
	// 判断等级是否启用
	lv := lg.GetLevelById(levelId)
	if lv.Enabled == 0 {
		return false
	}
	origin := m.value.Level
	unix := time.Now().UTC().Unix()
	m.value.Level = levelId
	m.value.UpdateTime = unix
	_, err := m.Save()
	if err == nil {
		m.level = nil
		lvLog := &member.LevelUpLog{
			MemberId:    m.GetAggregateRootId(),
			OriginLevel: origin,
			TargetLevel: levelId,
			IsFree:      1,
			PaymentId:   0,
			Reviewed:    enum.ReviewConfirm,
			CreateTime:  unix,
		}
		_, err = m.rep.SaveLevelUpLog(lvLog)
	}
	return true
}

// 增加经验值,订单成交的时候调用
func AddExp(exp int32) error {
	m.value.Exp += exp
	_, err := m.Save()
	//判断是否升级
	m.checkLevelUp()
	return err
}
*/



